package io.renren.modules.nas.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.utils.*;
import io.renren.modules.nas.dao.UploadFileDao;
import io.renren.modules.nas.entity.UploadFileEntity;
import io.renren.modules.nas.service.UploadFileService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@Service("uploadFileService")
public class UploadFileServiceImpl extends ServiceImpl<UploadFileDao, UploadFileEntity> implements UploadFileService {

    @Override
    public ArrayList<Integer> uploadFile(MultipartFile[] multipartFiles, Integer agentId) {
        // 判空，文件是否为空
        if (multipartFiles != null && multipartFiles.length != 0) {
            //判断文件目录是否存在，获取当天的时间
            ArrayList<Integer> uploadFileIds = new ArrayList<>();
            try {
                for (MultipartFile multipartFile : multipartFiles) {
                    if (multipartFile.isEmpty() || StringUtil.isNull(multipartFile.getOriginalFilename())) {
                        continue;
                    }

                    UploadFileEntity uploadFileEntity = new UploadFileEntity();
                    uploadFileEntity.setOrignalFileName(multipartFile.getOriginalFilename());
                    uploadFileEntity.setClientType(StringUtils.isNotBlank(HttpContextUtils.getClientType()) ? Integer.parseInt(HttpContextUtils.getClientType()) : 1);
                    uploadFileEntity.setDeleted(0);
                    uploadFileEntity.setStatus(0);
                    uploadFileEntity.setCreateTime(DateUtils.getCurrentDate());
                    this.baseMapper.insert(uploadFileEntity);
                    boolean flag = uploadFileAndWrapperEntity(multipartFile, uploadFileEntity);
                    if (!flag) {
                        throw new RRException("图片上传失败，请重新再试！");
                    }

                    if (agentId != null) {
                        // 上传用户类型（0：后台用户；1：代理用户） 此接口只用于代理端所以直接设置为1即可
                        uploadFileEntity.setUploadUserType(1);
                        // 上传用户ID，此处固定为代理的id
                        uploadFileEntity.setUploadUserId(agentId);
                    } else {
                        // 上传用户类型（0：后台用户；1：代理用户） 此接口只用于代理端所以直接设置为1即可
                        uploadFileEntity.setUploadUserType(0);
                        // 上传用户ID，此处固定为代理的id
                        uploadFileEntity.setUploadUserId(0);
                    }

                    this.baseMapper.updateById(uploadFileEntity);
                    uploadFileIds.add(uploadFileEntity.getId());
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new RRException("图片上传失败，请重新再试！");
            }
            return uploadFileIds;
        } else {
            throw new RRException("图片列表为空！无法上传");
        }
    }

    @Override
    public Integer uploadFile(MultipartFile multipartFile, Integer agentId) {
        MultipartFile[] multipartFiles = new MultipartFile[1];
        multipartFiles[0] = multipartFile;
        List<Integer> result = uploadFile(multipartFiles, agentId);
        if (!ListUtils.isEmpty(result)) {
            return result.get(0);
        }
        return null;
    }

    @Override
    public UploadFileEntity uploadFileReturnPojo(MultipartFile multipartFile, Integer agentId) {
        MultipartFile[] multipartFiles = new MultipartFile[1];
        multipartFiles[0] = multipartFile;
        List<Integer> result = uploadFile(multipartFiles, agentId);
        if (!ListUtils.isEmpty(result)) {
            return baseMapper.selectById(result.get(0));
        }
        return null;
    }

    private boolean uploadFileAndWrapperEntity(MultipartFile multipartFile, UploadFileEntity uploadFileEntity) throws IOException {
        String ossBasePath = UploadFilePathToUrlUtils.getOssPath();
        String originalFilename = multipartFile.getOriginalFilename();
        String relativePath = FileUtil.getFileStorePath(originalFilename, uploadFileEntity.getId());
        File finalFile = new File(ossBasePath + relativePath);

        FileUtil.createNewFile(finalFile);
        multipartFile.transferTo(finalFile);
        if (!finalFile.exists()) {
            return false;//文件存储失败
        }
        String fileName = finalFile.getName();
        uploadFileEntity.setFileName(FileUtil.getFileNameNoEx(fileName));
        uploadFileEntity.setFileSuffix(FileUtil.getExtensionName(fileName));
        uploadFileEntity.setFilePath(relativePath);
        uploadFileEntity.setFileMd5(FileUtil.getFileMD5(finalFile.getPath()));
        uploadFileEntity.setFileSize(multipartFile.getSize());
        uploadFileEntity.setFileType(FileUtil.checkFileType(originalFilename));
        uploadFileEntity.setStatus(1);
        uploadFileEntity.setModifyTime(DateUtils.getCurrentDate());
        return true;
    }
}
